$(function () {
    $('a').bind('focus', function () {
        if (this.blur) { //如果支持 this.blur   
            this.blur();
        }
    });
})
$.extend(huajun, {
    regs: function () {
        var regs = {
            all: {
                reg: /^[\w\u4e00-\u9fa5]+$/, desc: "中文，字母,数字或下划线！"
            }, common: {
                reg: /^\w+$/, desc: "字母,数字或下划线！"
            }, fangle: {
                reg: /[\uFF00-\uFFFF]/, desc: "全角字符!"
            }, vcode: {
                reg: /^\d{4}$/, desc: "4位数字！"
            }, email: {
                reg: /^\w[\w\.-]*@[\w-]+(\.[\w-]+)+$/, desc: "邮箱格式！"
            }, idcard: {
                reg: /^(\d{15}|\d{17}[\dx])$/, desc: "15或18位身份证号码！"
            }, chinese: {
                reg: /^[\u4E00-\u9FAF]+$/, desc: "中文！"
            }, truename: {
                reg: /^[\u4E00-\u9FAF]{2,4}$/, desc: "2-4个中文！"
            }, english: {
                reg: /^[A-Za-z]+$/, desc: "英文！"
            }, date: {
                reg: /^\d{4}-\d{2}-\d{2}$/i, desc: "公历日期(2013-07-06)！"
            }, url: {
                reg: /^http(s)?:\/\//i, desc: "URL！"
            }, qq: {
                reg: /^[1-9]\d{4,10}$/, desc: "5-11位QQ号！"
            }, phone: {
                reg: /^((((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?)|(\d{11}))$/,
                desc: "电话或手机号码！"
            }, mobile: {
                reg: /^(\d{1,4}\-)?(13|15|18){1}\d{9}$/, desc: "手机号码！"
            }, symbol: {
                reg: /[`~!@#$%^&*()+=|{}':;',.<>/ ? ~！@#￥ % …… & *（）—— + |{}【】'；：""'。，、？] /, desc: "特殊字符！"
            }, password: {
                reg: /^\w+$/, desc: "字母和数字或下划线"
            }, ip: {
                reg: /^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))$/,
                desc: "IP地址"
            }, mac: {
                reg: /[A-F\d]{2}:[A-F\d]{2}:[A-F\d]{2}:[A-F\d]{2}:[A-F\d]{2}:[A-F\d]{2}/i, desc: "MAC地址"
            }, number: {
                reg: /^\d+$/, desc: "数字"
            }, unnumber: {
                reg: /\D/, desc: "不为数字"
            }, integer: {
                reg: /^-?(0|[1-9]\d*)$/, desc: "整数！"
            }, positiveDecimal: {
                reg: /^\d+\.\d+$/, desc: "正小数"
            }
        }
        return regs;
    },
    /**
     * 校验表单
     */
    checkForm: function (formObj) {
        var inputs = formObj.find("input[checkData]");
        var resutl = true;
        formObj.find(".error").remove();
        formObj.find("input").removeClass("warn");
        formObj.find("select").removeClass("warn");
        formObj.find("textarea").removeClass("warn");
        var selectes = formObj.find("select[checkData]");
        var textareas = formObj.find("textarea[checkData]");
        for (var i = 0, _len = selectes.length; i < _len; i++) {
            inputs.push(selectes.eq(i));
        }

        for (var i = 0, _len = textareas.length; i < _len; i++) {
            inputs.push(textareas.eq(i));
        }

        for (var i = 0, _len = inputs.length; i < _len; i++) {
            var input = $(inputs[i]);
            var checkDataStr = input.attr("checkData");
            var placeholderData = input.attr("placeholder");
            var value = $.trim(input.val());
            value = value == placeholderData ? "" : value;
            if (null != checkDataStr) {
                var checkData = eval('(' + checkDataStr + ')');
                var msg = checkData.msg;
                msg = msg == null ? "输入不合法" : msg;
                /**
                 * 判断最大长度
                 */
                var max = checkData.max;
                if (null != max && value.length > max) {
                    this.setError(input, msg);
                    resutl = false;
                }

                /**
                 * 判断最小长度
                 */
                var min = checkData.min;
                if (null != min && value.length < min) {
                    this.setError(input, msg);
                    resutl = false;
                }

                /**
                 * 正则
                 */
                var reg = checkData.reg;
                if (null != reg && !this.regs()[reg].reg.test(value)) {
                    this.setError(input, msg);
                    resutl = false;
                }

                /**
                 * 必填
                 */
                var rq = checkData.rq;
                if (rq != null && value == "") {
                    this.setError(input, msg);
                    resutl = false;
                }
                /**
                 * 数字
                 */
                var number = checkData.number;
                if (number && value != "" && !this.regs().number.reg.test(value)) {
                    this.setError(input, msg);
                    resutl = false;
                }
                /**
                 * 电话或者手机号码
                 */
                var phone = checkData.phone;
                if (phone && value != "" && !this.regs().phone.reg.test(value)) {
                    this.setError(input, msg);
                    resutl = false;
                }
                /**
                 * QQ号码
                 */
                var qq = checkData.qq;
                if (qq && value != "" && !this.regs().qq.reg.test(value)) {
                    this.setError(input, msg);
                    resutl = false;
                }
                /**
                 * common
                 */
                var common = checkData.common;
                if (common && value != "" && !this.regs().common.reg.test(value)) {
                    this.setError(input, msg);
                    resutl = false;
                }
                /**
                 * 金额
                 */
                var positiveDecimal = checkData.positiveDecimal;
                if (positiveDecimal && value != "" && !this.regs().positiveDecimal.reg.test(value)) {
                    this.setError(input, msg);
                    resutl = false;
                }
            }
        }
        return resutl;
    },
    /**
     * 设置表单错误提示
     */
    setError: function (obj, msg) {
        obj.addClass("warn");
        if (obj.next().length == 0) {
            obj.after($("<div class='error'><span class='msg-error-icon'></span><span class='msg-error-info'>" + msg + "</span><span class='dir'></span></div>"));
        }
        obj.focus();
    },
    /**
     * 提示框
     */
    tipMsg: function (config) {
        var type = config.type;
        var content = config.content;
        var timeout = config.timeout;
        var fun = config.fun;
        var icon = "";
        var tit = "";
        switch (type) {
            case "loading":
                icon = "loading";
                break;
            case "success":
                icon = "success-icon";
                tit = "成功";
                break;
            case "error":
                icon = "error-icon";
                tit = "错误";
                break;
            default:
                icon = "";
        }
        var d;
        if (type == "loading") {
            var content = "<div class='dialog-tip-msg'><div class='dialog-tip-msg-icon " + icon + "'></div><div class='dialog-tip-msg-content'>" + content + "</div></div>";
            var d = dialog({
                content: content
            });

        } else {
            var content = "<div class='dialog-tip-msg'><div class='dialog-tip-msg-content'>" + content + "</div></div>";
            var d = dialog({
                title: "<div class='tip-msg-title'><i class='" + icon + "'></i><span>" + tit + "提示</span></div>",
                content: content
            });
        }
        if (type == "success") {
            d.show();
        } else {
            d.showModal();
        }

        if (null !== timeout && typeof (timeout) != "undefined" && timeout != 0) {
            setTimeout(function () {
                d.remove();
                fun == null ? "" : fun();
            }, timeout)
        }
        return d;
    },
    /***弹出框***/
    dialog: function (config) {
        var title = config.title
        var content = config.content;
        var okfun = config.okfun;
        var cancelfun = config.cancelfun;
        var align = config.align;
        var dialog_height = $(window).height() - 200;
        content = "<div style='max-height:" + dialog_height + "px;overflow-y:auto;overflow-x:hidden'>" + content + "</div>";
        var d = dialog({
            title: title, content: content, button: [{
                value: '取消'
            }, {
                value: '确定', callback: function () {
                    if (okfun != null) {
                        okfun();
                        return false;
                    }
                }, autofocus: true
            }]
        });
        d.showModal();
        return d;
    },
    /***确认框****/
    confirm: function (config) {
        var content = config.msg || "你确认要执行操作吗?";
        var fun = config.fun;
        var content = "<div class='dialog-tip-msg'><div class='dialog-tip-msg-icon warn'></div><div class='dialog-confirm-content'>" + content + "</div></div>";
        var d = dialog({
            title: "确认提示", content: content, okValue: '确定', ok: function () {
                fun == null ? "" : fun();
            }, cancelValue: '取消', cancel: function () {
            }
        });
        d.showModal();
        return d;
    },
    /**
     * ajax请求
     */
    ajaxRequest: function (config) {
        var async = config.asycn = null ? true : config.asycn;
        var url = config.url;
        var data = config.data || "";
        var fun = config.fun;
        var showLoad = config.showLoad == null ? true : config.showLoad;
        if (showLoad) {
            var d = this.tipMsg({
                type: "loading", content: "加载中......"
            });
        }

        var that = this;
        $.ajax({
            async: async, cache: false, type: 'POST', dataType: "json", data: data, url: url,
            // 请求的action路径
            success: function (response) {
                if (showLoad) {
                    d.remove();
                }
                if (response.responseCode.code == huajun.resultCode.LOGINTIMEOUT) { // 超时
                    var url = huajun.curUrl;
                    that.goLogin();
                } else if (response.responseCode.code == huajun.resultCode.SUCCESS) { // 请求成功
                    fun(response);
                } else if (response.responseCode.code == huajun.resultCode.MOREMAXLOGINCOUNT) {
                    $("#refreshCheckCode").find("img").attr("src", "checkCode.do?" + new Date().getTime());
                    fun(response);
                } else if (response.responseCode.code == huajun.resultCode.NOPERMISSION) { // 没有权限
                    that.tipMsg({
                        type: "error", content: response.errorMsg, timeout: 3000
                    });
                } else if (response.responseCode.code == huajun.resultCode.CODEERROR) { // 验证码错误
                    that.tipMsg({
                        type: "error", content: response.errorMsg, timeout: 3000
                    });
                    $("#refreshCheckCode").find("img").attr("src", "checkCode.do?" + new Date().getTime());
                } else { // 错误
                    that.tipMsg({
                        type: "error", content: response.errorMsg, timeout: 3000
                    });
                    $("#refreshCheckCode").find("img").attr("src", "checkCode.do?" + new Date().getTime());
                }
            }
        });
    },
    /*************datagrid*****************/
    initDataGrid: function () {
        //计算左侧操作栏高度
        var document_height = $(window).height();
        $(".op-group-panel .con").css({"height": document_height + "px"});
        //点击操作按钮展开操作区域
        $(document).on("click", ".grid-op-btn-s a", function () {
            var type = $(this).attr("type");
            var right = "15px";
            if (type == "hide") {
                right = "70px";
                $(this).attr("type", "show");
                $(".op-group-panel").fadeIn(600, function () {
                    $(".op-group-panel span.dir").show();
                });

            } else {
                $(this).attr("type", "hide");
                $(".op-group-panel").fadeOut(400, function () {
                    $(".op-group-panel span.dir").hide();
                });
            }
            $(".grid-op-btn-s").animate({
                right: right
            }, 500);

        });
        //初始化全选
        $(document).on("click", "tr.data-grid-title th input", function () {
            if ($(this).is(":checked")) {
                $(this).parent().parent().parent().find("tr td input[name='id']").prop("checked", true);
            } else {
                $(this).parent().parent().parent().find("tr td input[name='id']").prop("checked", false);
            }

        });

    },
    /***********折叠*************/
    accordion: function () {
        $(document).on("click", ".btn-fold", function () {
            var type = $(this).attr("type");
            if (type == "open") {
                $(this).parent().parent().parent().find("form").slideUp(500);
                $(this).attr("type", "close");
                $(this).removeClass("up");
                $(this).addClass("down");
            } else {
                $(this).parent().parent().parent().find("form").slideDown(500);
                $(this).attr("type", "open");
                $(this).removeClass("down");
                $(this).addClass("up");
            }
        });
    },
    tagInit: function () {
        $(".tag").each(function () {
            $(this).find(".tag-container").eq(0).find(".tag-content").eq(0).show();
            $(this).find(".tag-title").eq(0).find("a").eq(0).addClass("active");
            $(this).find(".tag-title").eq(0).find("a").each(function (index) {
                $(this).attr("index", index);
            });
        });

        $(document).on("click", ".tag .tag-title a", function () {
            $(this).parent().find("a").removeClass("active");
            $(this).addClass("active");
            var tag_contents = $(this).parent().parent().find(".tag-container").find(".tag-content");
            tag_contents.hide();
            tag_contents.eq($(this).attr("index")).show();
        });
    }


});

$.ajaxSetup({
    dataFilter: function(data, type) {
        if(data){
            var msg = eval("(" + data + ")");
            if (msg.status == 401) {
                top.application.reLogin();
                return;
            }
            return data;
        }
        return data;
    }
});